/*
 * @lc app=leetcode.cn id=105 lang=golang
 *
 * [105] 从前序与中序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

// type TreeNode struct {
// 	Val   int
// 	Left  *TreeNode
// 	Right *TreeNode
// }

func buildTree(preorder []int, inorder []int) *TreeNode {
	if len(preorder) == 0 {
		return nil
	}
	rootVal := preorder[0]
	i := 0
	for i < len(inorder) && inorder[i] != rootVal {
		i++
	}
	left := buildTree(preorder[1:1+i], inorder[:i])
	right := buildTree(preorder[i+1:], inorder[i+1:])
	return &TreeNode{Val: rootVal, Left: left, Right: right}
}

// @lc code=end
